package main

import (
	"app/internal/app/model"
	router "app/internal/app/router"
	"app/internal/pkg/config"
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	// 引入配置
	config.InitConfig("configs/config.ini")
	// 引用数据库
	model.InitDB()

	// 引入路由组件
	router := router.InitRouter()
	srv := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", config.Domain, config.Port),
		Handler: router,
	}
	// 协程启动服务器
	go runServer(srv)

	// 等待中断信号以优雅地关闭服务器
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	// 关闭HTTP服务器
	log.Println("Shutdown Server ...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Print("Server Shutdown error:", err)
	}

	// 关闭数据库连接
	log.Print("Closing DB Connection...")
	if err := model.CloseDB(); err != nil {
		log.Print("DB close error:", err)
	}

	log.Println("Server exiting")
}

func runServer(srv *http.Server) {
	var err error
	if config.Https {
		log.Printf("Listening and serving HTTPS on https://%s", srv.Addr)
		err = srv.ListenAndServeTLS(config.CertFile, config.KeyFile)
	} else {
		log.Printf("Listening and serving HTTP on http://%s", srv.Addr)
		err = srv.ListenAndServe()
	}

	if err != nil && err != http.ErrServerClosed {
		log.Fatalf("listen error: %s\n", err)
	}
}
